# -*- coding:utf-8 -*- #
from utils import get_item_ids,get_contents,get_oid_by_item_id,execute_sql,query_sql
from jsondata import json2proxy,s2datetime,jsondumps

#引入上层目录模块方法
import sys
sys.path.append("..")

from configure import logger_path
from logger.logger import getlogger


class FastDb(object):

    def __init__(self):
        #self.p = redis_pipe()
        pass


    def save2monitor(self, data):
        
        '''
        保存监控采集的数据
        
        data = {"内存使用": [3920, "MB"], 
             "datetime": 1333695036, 
             "内存剩余":[175, "MB"], 
             "id": 180, 
             "is_attention": 1} 
             
        '''
        try:
            datetime = data.pop('datetime')
            # is_attention 默认为 0 ，如果字典中不存在，就赋给0，存在 则使用字典中的值
            is_attention = data.pop('is_attention', 0)
            item_id = int(data.pop('id'))
        except KeyError as e:
            getlogger(logger_path).error('has not key:%s' % e.message)
            return

        '''
        data处理后的内容
        data = {"内存使用": [3920, "MB"], 
             "内存剩余":[175, "MB"]
             } 
        '''
        content = jsondumps(data, False)
        # content = {"内存使用": [173, "MB"], "内存剩余": [3922, "MB"]} json后是中文 不是u

        sql = u"insert into m_monitor(item_id,\
        date_time, is_attention, content) values('%s', '%s',\
        '%s', '%s')" % (item_id, datetime, is_attention, content)
        
        execute_sql(sql)

    def save2alarm(self, data):
        """
        level == 0: hset 'a'.id.'disarm_time' begin_time endtime
        level != 0: hincrby 'a'.id.'level' begin_time 1
        and hset 'a'.id begin_time content
        """

        level = data.pop('level', 0)
        try:
            begin_time = data.pop('begin_time')
            datetime = begin_time
        except:
            end_time = data.pop('end_time')
            datetime = end_time

        item_id = data.pop('id')
        content = jsondumps(data, False)

        sql_count = "select count(item_id) from m_alarm where item_id='%s' LIMIT 1" % (item_id)

        count = query_sql(sql_count)

        if level == 0:
            sql = "delete from m_alarm where item_id='%s' LIMIT 1" % (item_id)
        else:
            if count[0][0]:
                sql = u"update m_alarm set end_time='%s',level='%s', content='%s' LIMIT 1" \
                       % (begin_time,level, content)
    
            else:
                sql = u"insert into m_alarm(item_id, begin_time,\
                        level, content) values('%s', '%s',\
                        '%s', '%s')" % (item_id, begin_time,level, content)

            
        execute_sql(sql)
        
        sql_begin_time = "select begin_time from m_alarm where item_id='%s' LIMIT 1" % (item_id)
        last_record_begin_time = query_sql(sql_begin_time)
        
        self.propelling(item_id, content, last_record_begin_time, datetime, level)
        
        
    def delete2alarm(self, item_id):
        sql = "delete from m_alarm where item_id='%s' LIMIT 1" % (item_id)
        try:
            execute_sql(sql)
        except:
            #没有报警数据对饮的id号
            pass
        
    def propelling(self, item_id, content, last_record_begin_time, datetime,level):
        from propeller.notifiter import Notifiter
        oid = get_oid_by_item_id(item_id)
        print 'oid', oid
        if oid:
            Notifiter.notify({'oid': oid[0], 'item_id': item_id, 'content':
                content, 'begin_time':  last_record_begin_time, 'last_time':
                datetime, 'cur_level': level}, level)
            
    def save2logger(self, data):
        #print data
        try:
            datetime = data.pop('datetime')
            content = jsondumps(data.pop('error'), False)
            item_id = int(data.pop('id'))
        except KeyError as e:
            getlogger(logger_path).error('has not key:%s' % e.message)
            return

        #content = json.dumps(data)

        self.p.rpush(item_id, datetime)
        self.p.hset('%s.%s' % (item_id, datetime), 0, content)
        self.p.expire('%s.%s' % (item_id, datetime), EXPIRE_TIME)
        self.p.set('%s.l_last_time', datetime)
        self.p.incr('%s.l_count' % item_id)
        self.p.expire('%s.l_last_time', EXPIRE_TIME)
        self.p.expire('%s.l_count', EXPIRE_TIME)
        self.p.execute()
        self._remlist(item_id, datetime)

        sql = "insert into ma_log_data(item_id, log_time, content) \
                values('%s', '%s', '%s')" % (item_id, s2datetime( datetime), content)
        execute_sql(sql, True)

    def query(self, transport, data):
        try:
            table = data['table']
            oid = data['oid']
            time = data.get('time')
            num = data.get('num')
        except KeyError as e:
            transport.write('{"error_msg": "KeyError %s"}' % e.message)
            getlogger(logger_path).error('has not key:%s' % e.message)
            return

        item_ids = []
        oids = []
        for k, v in oid.iteritems():
            if len(v) > 0:
                item_ids.extend(v)
            else:
                oids.append(k)
        if oids:
            item_ids.extend(get_item_ids(oids))

        if not item_ids:
            transport.write(json2proxy({"error_msg": "no items"}))
            print json2proxy({"error_msg": "no items"})
        else:
            contents = get_contents(table, item_ids, time, num)
            contents = json2proxy(contents)
            print item_ids, contents
            transport.write(contents)

